/**
 * date:2020/02/27
 * author:Mr.Chung
 * version:2.0
 * description:layuimini 菜单框架扩展
 */
layui.define(['element', 'laytpl'], function (exports) {
    const element = layui.element,
          $ = layui.$,
          laytpl = layui.laytpl,
          layer = layui.layer;

    const jpMenu = {

        /**
         * 菜单初始化
         * @param options.menuList   菜单数据信息
         * @param options.multiModule 是否开启多模块
         * @param options.menuChildOpen 是否展开子菜单
         */
        render: function (options) {
            options.menuList = options.menuList || [];
            options.multiModule = options.multiModule || false;
            options.menuChildOpen = options.menuChildOpen || false;
            if (options.multiModule) {
                this.renderMultiModule(options.menuList, options.menuChildOpen);
            } else {
                this.renderSingleModule(options.menuList, options.menuChildOpen);
            }
            this.listen();
        },

        /**
         * 单模块
         * @param menuList 菜单数据
         * @param menuChildOpen 是否默认展开
         */
        renderSingleModule: function (menuList, menuChildOpen) {
            menuList = menuList || [];
            var leftMenuHtml = '',
                childOpenClass = '',
                leftMenuCheckDefault = 'layui-this';
            var me = this;
            if (menuChildOpen) childOpenClass = ' layui-nav-itemed';
            leftMenuHtml = this.generateLeftMenu(menuList, {childOpenClass: childOpenClass});
            $('.layui-layout-body').addClass('layuimini-single-module'); //单模块标识
            $('.layuimini-header-menu').remove();
            $('.layuimini-menu-left').html(leftMenuHtml);

            element.init();
        },
        generateMenu: function (menu, isSub) {
            let html = '';
            if (isSub) {
                html = `<dd class="{{- d.childOpenClass }} {{- d.className }}">
                            <a href="javascript:;" {{# if((!d.child || !d.child.length) && d.href){ }}layuimini-href="{{- d.href }}"{{# } }} {{# if(d.menu){ }}data-menu="{{- d.menu }}"{{# } }} {{# if(d.id){ }}id="{{- d.id }}"{{# } }} {{# if(d.target){ }}target="{{- d.target }}"{{# } }}>
                                {{# if(d.icon){ }} <i class="{{- d.icon }}"></i> {{# } }}
                                <span> {{- d.title }}</span>
                            </a>
                            {{# if(d.children){ }} {{- d.children }} {{# } }}
                        </dd>`;
            } else {
                html =
                    `<li class="layui-nav-item {{- d.childOpenClass }} {{- d.className }}" {{# if(d.id){ }} id="{{- d.id }}" {{# } }} {{# if(d.menu){ }} data-menu="{{- d.menu }}" {{# } }}>
                        <a href="javascript:;" {{# if(d.target){ }}target="{{- d.target }}"{{# } }} {{# if(d.href){ }} layuimini-href="{{- d.href }}" {{# } }}>
                            {{# if(d.icon){ }}<i class="{{- d.icon }}"></i>{{# } }}
                            <span>{{- d.title }}</span>
                        </a>
                        {{# if(d.children){ }} {{- d.children }} {{# } }}
                    </li>`;
            }
            return laytpl(html).render(menu);
        },
        /**
         * 生成菜单
         */
        compileMenu: function (menu, isSub) {
            let menuHtml =
                `<li {{# if(d.menu){ }} data-menu="{{- d.menu }}" {{# } }} class="layui-nav-item menu-li {{- d.childOpenClass }} {{- d.className }}"  {{# if(d.id){ }}  id="{{- d.id }}" {{# } }}>
                    <a {{# if(d.href){ }} layuimini-href="{{- d.href }}" {{# } }} {{# if(d.target){ }}  target="{{- d.target }}" {{# } }} href="javascript:;">
                        {{# if(d.icon){ }}
                        <i class="{{- d.icon }}"></i>
                        {{# } }}
                        <span>{{- d.title }}</span>
                    </a>
                    {{# if(d.children){ }} {{- d.children }} {{# } }}
                </li>`;
            if (isSub) {
                menuHtml =
                    `<dd class="menu-dd {{- d.childOpenClass }} {{- d.className }}">
                        <a href="javascript:;"  {{# if(d.menu){ }} data-menu="{{- d.menu }}" {{# } }} {{# if(d.id){ }} id="{{- d.id }}" {{# } }} {{# if((!d.child || !d.child.length) && d.href){ }} layuimini-href="{{- d.href }}" {{# } }} {{# if(d.target){ }} target="{{- d.target }}" {{# } }}>
                            {{# if(d.icon){ }} <i class="{{- d.icon }}"></i> {{# } }}
                            <span class="layui-left-nav"> {{- d.title }}</span>
                        </a>
                        {{# if(d.children){ }} {{- d.children }} {{# } }}
                    </dd>`;
            }
            return laytpl(menuHtml).render(menu);
        },
        compileMenuContainer: function (menu, isSub) {
            if (!menu.children) {
                return '';
            }
            let wrapperHtml =
                `<ul class="layui-nav layui-nav-tree {{- d.className }}" id="{{- d.id }}">
                    {{- d.children }}
                </ul>`;
            if (isSub) {
                wrapperHtml = `<dl class="layui-nav-child">{{- d.children }}</dl>`;
            }
            return laytpl(wrapperHtml).render(menu);
        },
        each: function (list, callback) {
            let _list = [];
            for (let i = 0, length = list.length; i < length; i++) {
                _list[i] = callback(i, list[i]);
            }
            return _list;
        },
        generateChildrenMenu: function (menuList, options) {
            const menuHtml = [];
            const othis = this;
            menuList = menuList || [];
            layui.each(menuList, (index, item) => {
                // 1. 若有子菜单，则递归生成子菜单
                if (layui.isArray(item.child) && item.child.length > 0) {
                    item.children = othis.generateChildrenMenu(item.child, {childOpenClass: options.childOpenClass || ''});
                }
                // 2. 生成最外层菜单
                item.className = '';
                item.childOpenClass = options.childOpenClass || '';
                menuHtml.push(othis.generateMenu(item, true));
            });
            return othis.compileMenuContainer({children: menuHtml.join('')}, true);
            // var html = this.each(menuList, function (idx, menu) {
            //     if (menu.child && menu.child.length > 1) {
            //         menu.children = othis.generateChildrenMenu(menu.child, {childOpenClass: options.childOpenClass || ''});
            //     }
            //     menu.className = "";
            //     menu.childOpenClass = options.childOpenClass || '';
            //     return othis.compileMenu(menu, true);
            // }).join("");
            // return othis.compileMenuContainer({children: html}, true);
        },
        /**
         *
         * @param menuData 菜单数据，可以是Array | Object
         * @param childOpenClass
         */
        generateMenuNew: function (menuData, childOpenClass) {
            if (!menuData) {
                return '';
            }

            // 1. 处理 menuData.child 子菜单
            let childrenHtmlStr = '';
            let childMenus = menuData.child;
            if (layui.isArray(childMenus) && childMenus.length > 1) {
                for (let i = 0; i < childMenus.length; ++i) {
                    // 递归生成
                    let childrenMenuItemHtml = this.generateMenuNew(childMenus[i], childOpenClass);
                    let oneStr = `<dd>
                                            <a href="{{- d.href ? d.href : 'javascript:;' }}" {{# if(d.target){ }}target="{{- d.targrt }}"{{# } }}>
                                                {{# if(d.icon){ }}
                                                <i class="{{- d.icon }}"></i>
                                                {{# } }}
                                                <span>{{- d.title }}</span>
                                            </a>
                                            </dd>`
                    childrenHtmlStr += laytpl(oneStr).render(childMenus[i])
                }

                let tpl = `<li class="layui-nav-item">
                                      <a href="javascript:;">默认收缩</a>
                                      <dl class="layui-nav-child">
                                      {{  }}
                                      <dl>
                                  </li>`;
                laytpl(tpl).render()

            }
            let menuHtml =
                `<li class="layui-nav-item">
                    <a href="{{# d.href ? d.href : 'javascript:;' }}" {{# if(d.target){ }}target="{{- d.target }}"{{# } }}>
                        {{# if(d.icon){ }}<i class="{{- d.icon }}"></i>{{# } }}
                        <span>${menuData.title}</span>
                    </a>
                    {{- d.childrenHtml }}
                </li>`;
            menuData.childrenHtml = childrenHtmlStr;
            return laytpl(menuHtml).render(menuData);
        },
        generateLeftMenu: function (leftMenus, options) {
            let othis = this;
            let leftMenusHtml = [];
            options = options || {};

            // 1. 生成菜单
            layui.each(leftMenus || [], (index, leftMenu) => {
                // 1. 生成菜单
                // let menuHtml = this.generateMenuNew(leftMenu, options.childOpenClass);
                let childMenus = othis.generateChildrenMenu(leftMenu.child, {childOpenClass: options.childOpenClass});
                // 2. 生成当前菜单项
                let menuItemHtml = othis.generateMenu({
                    href: leftMenu.href,
                    target: leftMenu.target,
                    childOpenClass: options.childOpenClass,
                    icon: leftMenu.icon,
                    title: leftMenu.title,
                    children: childMenus,
                    className: '',
                });
                leftMenusHtml.push(menuItemHtml);
            });

            // 3. 包装整个菜单
            return othis.compileMenuContainer({
                id: options.parentMenuId,
                className: options.leftMenuCheckDefault,
                children: leftMenusHtml.join('')
            });
        },
        /**
         * 多模块
         * @param menuList 菜单数据
         * @param menuChildOpen 是否默认展开
         */
        renderMultiModule: function (menuList, menuChildOpen) {
            menuList = menuList || [];
            let othis = this;
            let headerMenuHtml = [],
                headerMobileMenuHtml = [],
                sideMenuHtml = [],
                leftMenuCheckDefault = 'layui-this',
                childOpenClass = '',
                headerMenuCheckDefault = 'layui-this';

            if (menuChildOpen) {
                childOpenClass = ' layui-nav-itemed';
            }

            // 渲染菜单 start
            layui.each(menuList, (index, item) => {
                let menu = 'multi_module_' + index,
                    id = menu + 'HeaderId',
                    topMenuItemHtml = '',
                    sideMenuItemHtml = '',
                    headerMobileMenuItemHtml = '';
                // 1. 顶部菜单开始
                topMenuItemHtml = othis.compileMenu({
                    className: headerMenuCheckDefault,
                    menu,
                    id,
                    title: item.title,
                    href: '',
                    target: '',
                    children: ''
                });
                headerMenuHtml.push(topMenuItemHtml);
                // 2. 生成移动端头部菜单
                headerMobileMenuItemHtml = othis.compileMenu({id, menu, icon: item.icon, title: item.title}, true);
                headerMobileMenuHtml.push(headerMobileMenuItemHtml);
                // 3. 生成对应的左侧菜单
                sideMenuItemHtml = othis.generateLeftMenu(item.child, {
                    parentMenuId: menu,
                    childOpenClass: childOpenClass,
                    leftMenuCheckDefault: leftMenuCheckDefault
                });
                sideMenuHtml.push(sideMenuItemHtml);
                // 默认选中第一个头部菜单，之后的都不选中
                headerMenuCheckDefault = '';
                // 只显示第一个，之后的菜单都隐藏
                leftMenuCheckDefault = 'layui-hide';
            });

            $('.layui-layout-body').addClass('layuimini-multi-module'); //多模块标识
            $('.layuimini-menu-header-pc').html(headerMenuHtml.join('')); //电脑
            $('.layuimini-menu-header-mobile').html(headerMobileMenuHtml.join('')); //手机
            $("#jpMenuLeft").html(sideMenuHtml.join(''));
            // 渲染所有元素
            element.init();
        },

        /**
         * 监听
         */
        listen: function () {

            /**
             * 菜单模块切换
             */
            $('body').on('click', '[data-menu]', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var menuId = $(this).attr('data-menu');
                // header
                $(".layuimini-header-menu .layui-nav-item.layui-this").removeClass('layui-this');
                $(this).addClass('layui-this');
                // left
                $(".layuimini-menu-left .layui-nav.layui-nav-tree.layui-this").addClass('layui-hide');
                $(".layuimini-menu-left .layui-nav.layui-nav-tree.layui-this.layui-hide").removeClass('layui-this');
                $("#" + menuId).removeClass('layui-hide');
                $("#" + menuId).addClass('layui-this');
                layer.close(loading);
            });

            /**
             * 菜单缩放
             */
            $('body').on('click', '.layuimini-site-mobile', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var isShow = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (isShow == 1) { // 缩放
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 0);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').removeClass('layuimini-all');
                    $('.layui-layout-body').addClass('layuimini-mini');
                } else { // 正常
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                    $('.layui-layout-body').removeClass('layuimini-mini');
                    $('.layui-layout-body').addClass('layuimini-all');
                    layer.close(window.openTips);
                }
                element.init();
                layer.close(loading);
            });
            /**
             * 菜单缩放
             */
            $('body').on('click', '[data-side-fold]', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var isShow = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (isShow == 1) { // 缩放
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 0);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').removeClass('layuimini-all');
                    $('.layui-layout-body').addClass('layuimini-mini');
                    // $(".menu-li").each(function (idx,el) {
                    //     $(el).addClass("hidden-sub-menu");
                    // });

                } else { // 正常
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                    $('.layui-layout-body').removeClass('layuimini-mini');
                    $('.layui-layout-body').addClass('layuimini-all');
                    // $(".menu-li").each(function (idx,el) {
                    //     $(el).removeClass("hidden-sub-menu");
                    // });
                    layer.close(window.openTips);
                }
                element.init();
                layer.close(loading);
            });

            /**
             * 手机端点开模块
             */
            $('body').on('click', '.layuimini-header-menu.layuimini-mobile-show dd', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var check = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (check === "1") {
                    $('.layuimini-site-mobile').trigger("click");
                    element.init();
                }
                layer.close(loading);
            });
        },

    };


    exports("jpMenu", jpMenu);
});
